package sstable

import (
	"fmt"
	"log"
	"path/filepath"
	"time"
)

func getLevel(name string) (level uint32, index uint32, err error) {
	n, err := fmt.Sscanf(name, "%d.%d.db", &level, &index)
	if 2 != n || nil != err {
		return 0, 0, fmt.Errorf("文件名格式错误")
	}
	return level, index, nil
}

// 加载 DB 文件
func (tree *TableTree) loadDBFile(path string) {
	log.Println("Loading the ", path)
	start := time.Now()
	defer func() {
		elapase := time.Since(start)
		log.Println("Loading the ", path, "finished, cost time: ", elapase)
	}()

	level, index, err := getLevel(filepath.Base(path))
	if err != nil {
		return
	}

	table := &SSTable{}
	table.Init(path)

	newNode := &TableNode{
		index: index,
		table: table,
	}

	// 得到链表的头节点
	currentNode := tree.levels[level]

	if currentNode == nil {
		tree.levels[level] = newNode
		return
	}
	// 每一层形成一个链表
	if newNode.index < currentNode.index {
		newNode.next = currentNode
		tree.levels[level] = newNode
		return
	}

	// 将 SSTable 插入合适的位置
	for currentNode != nil {
		if currentNode.next == nil || newNode.index < currentNode.next.index {
			newNode.next = currentNode.next
			currentNode.next = newNode
			break
		} else {
			currentNode = currentNode.next
		}
	}

}
